package com.xzzz.irda.guardcat.core.metric.app;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.filter.GlobalFilter;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@ConditionalOnClass(value = GlobalFilter.class)
public class GatewayRelationUtil {

    @Autowired(required = false)
    private DiscoveryClient discoveryClient;

    @PostConstruct
    public void init() {
        if (discoveryClient == null) {
            return;
        }

        for (String serviceId : discoveryClient.getServices()) {
            List<ServiceInstance> services = discoveryClient.getInstances(serviceId);
            if (CollUtil.isNotEmpty(services)) {
                RELATION.add(services.get(0).getServiceId());
            }
        }
    }

    private static final Set<String> RELATION = new HashSet<>();

    public static Set<String> getRelation() {
        return RELATION;
    }

}
